package com.nettyRpc.consumer.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

/**
 * 客户端
 */

public class NettyClient {
    public Channel doOpen(String host, int port) {
        final EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        // 使用NioSocketChannel来作为连接用的channel类
        b.group(group).channel(NioSocketChannel.class)
                // 绑定连接初始化器
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) {
                        ChannelPipeline ph = ch.pipeline();
                        ph.addLast(new ObjectDecoder(1024, ClassResolvers.cacheDisabled(this.getClass().getClassLoader())));
                        ph.addLast(new ObjectEncoder());
                        //客户端处理类
                        ph.addLast(new DubboChannelHandler());
                    }
                });
        //发起异步连接请求，绑定连接端口和host信息
        ChannelFuture future = null;
        try {
            future = b.connect(host, port).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (future.isSuccess()) {
            System.out.println("连接服务器成功");

        } else {
            System.out.println("连接服务器失败");
            future.cause().printStackTrace();
            group.shutdownGracefully(); //关闭线程组
        }
        return future.channel();
    }
}
